package cn.uestc.labhms.modules.hms.service.impl;

import cn.uestc.labhms.common.utils.DateUtils;
import cn.uestc.labhms.modules.hms.entity.Vo.RevisePasswordVo;
import cn.uestc.labhms.modules.hms.exception.HMSException;
import cn.uestc.labhms.modules.hms.service.PasswordService;
import cn.uestc.labhms.modules.hms.util.EmailUtil;
import cn.uestc.labhms.modules.sys.dao.SysCaptchaDao;
import cn.uestc.labhms.modules.sys.dao.SysUserDao;
import cn.uestc.labhms.modules.sys.entity.SysCaptchaEntity;
import cn.uestc.labhms.modules.sys.entity.SysUserEntity;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Service
@Slf4j
public class PasswordServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptchaEntity> implements PasswordService {

    @Autowired
    private Producer producer;
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public void sendRevisePassEmail(String email) {
        String code = producer.createText();
        String subject = "HMS系统安全中心";
        String text = "【HMS】您的验证码为" + code + "，有效时间为3分钟，请您妥善保管！";
        EmailUtil.sendMail(email, subject, text);
        SysCaptchaEntity sysCaptchaEntity = new SysCaptchaEntity();
        sysCaptchaEntity.setCode(code);
        sysCaptchaEntity.setUuid(email);
        sysCaptchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 3));
        this.saveOrUpdate(sysCaptchaEntity);
    }

    @Override
    public void RevisePassword(RevisePasswordVo revisePasswordVo) {
        SysCaptchaEntity sysCaptchaEntity =
                this.getOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", revisePasswordVo.getEmail()));
        if (sysCaptchaEntity == null) {
            throw new HMSException("无此用户名或未给此用户发送过验证码");
        }
        // uuid即为用户邮箱（用户名）
        this.removeById(sysCaptchaEntity.getUuid());
        if (sysCaptchaEntity.getCode().equalsIgnoreCase(revisePasswordVo.getCaptcha())
                && sysCaptchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", sysCaptchaEntity.getUuid()).select("salt");
            SysUserEntity userEntity = sysUserDao.selectOne(queryWrapper);
            log.info("修改密码的用户为：{}", sysCaptchaEntity.getUuid());
            String salt = null;
            if (!ObjectUtils.isEmpty(userEntity)) {
                salt = userEntity.getSalt();
            } else {
                throw new HMSException("无此用户名");
            }
            UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("username", sysCaptchaEntity.getUuid())
                    .set("password", new Sha256Hash(revisePasswordVo.getPassword(), salt).toHex());
            sysUserDao.update(null, updateWrapper);
            return;
        }
        log.info("系统验证码：{}，用户传输验证码：{}", sysCaptchaEntity.getCode(), revisePasswordVo.getCaptcha());
        throw new HMSException("验证码错误或过期，请重新发送邮件获取验证码");
    }
}
